Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
Why can't I get "res" object console logged inside the callback of app.listen in node.js
const http = require('http') 
const server = http.createServer(()=>{
            console.log("created server")
        });
const port = 3000;
server.listen(port, (req,res) => {console.log(res)})

// in console => undefined

//after opening the page => in console => created server

// no res obj in console

why can't "res" be consolelogged even after "created server" is console logged and "http://localhost:3000" is opened too?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

why can't "res" be consolelogged even after "created server" is console logged

The callback to server.listen() just tells you when your server has been started. It is not passed req or res as there is no active incoming http connection at the moment your server has just started.

req and res get passed to listeners for the request event which you can register for either by passing a callback to http.createServer() as in:

const server = http.createServer((req, res) => {
    console.log(res);
    res.end("hello");
});

Or, by registering a listener for the request event as in:

server.on('request', (req, res) => {
    console.log(res);
    res.end("hello");
});

So, it appears in your code that you just have the callbacks to http.createServer() and server.listen() reversed. It's the one to http.createServer() that is called with req and res, not the callback to server.listen(). That callback to server.listen() tells you when the server has been successfully started. The callback to http.createServer() tells you when an incoming http request has arrived and it passes req and res to that callback.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda